import type { ProColumns } from '@ant-design/pro-components';
import { Button, Tag, Popconfirm, Switch, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import {
  ProTable,
  PageContainer, DrawerForm, ProFormText,
  TableDropdown,
} from '@ant-design/pro-components';
import IHttp from "@/services/http.service";
import AccountCreateForm from "@/pages/Account/List/AccountCreateForm";
import AccountBindPopover from "@/pages/Account/List/AccountBindPopover";
import {firstValueFrom, map} from "rxjs";
import { Link } from 'umi';

const AccountList: React.FC = () => {
  const ref = useRef<Ant.ProTableActionType>()
  const columns: ProColumns<API.AccountItem>[] = [
    {
      title: '账号名称',
      dataIndex: 'name',
      render: (_, record) => <a onClick={() => setEditItem({...record})}>{_}</a>,
    },
    {
      title: '平台',
      dataIndex: 'type',
      valueType: 'select',
      valueEnum: {
        1: { text: 'b站' },
        2: { text: '抖音' },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, record) => {
        const colorSet: {[prop: number]: string} = {
          0: "error", 1: "success", 2: "warning"
        }
        const textSet: {[prop: number]: string} = {
          0: "未绑定", 1: "已绑定", 2: "绑定过期"
        }
        return (
          <>
            <Tag color={colorSet[record.status]}>{textSet[record.status]}</Tag>
            {record.hook_user_action === 1 ? <Tag color={"success"}>养号中</Tag> : null}
          </>
        )
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 240,
      valueType: 'option',
      render: (_, record) => [
        <AccountBindPopover 
          key="link" 
          item={record} 
          onRefreshTable={() => {
            ref.current?.reload()
          }}
        />,
        <Link key="videos" to={`/account/${record.id}/posts`}>视频</Link>,
        <Popconfirm
          key="del"
          title="删除账号"
          description="确定要删除当前账号吗？"
          okText="确定"
          cancelText="取消"

          onConfirm={() => {
            return firstValueFrom(
              IHttp.delAccount(record.id).pipe(
                map(() => ref.current?.reload())
              )
            )
          }}
        >
          <a className="text-[#ff4d4f]">删除</a>
        </Popconfirm>,
        <TableDropdown
          key="actionGroup"
          onSelect={k => {
            if (k === "SmsSend") {
              smsSend(record)
              // showGetVideoConfig(record)
            }
            if (k === "SmsValidate") {
              setValidateSmsItem(record)
              // startPubTask(record)
            }

            if (k === "ShareCookie") {
              setShareCookieItem(record)
              // copyTask(record)
            }
            if (k === "CheckCookie") {
              checkAccountCookie(record)
              // copyTask(record)
            }
            if (k === "HookUserAction") {
              updateHookUserAction(record)
              // copyTask(record)
            }
            if (k === "OpenAccountHomePage") {
              
              openAccountHomePage(record)
            }
          }}
          menus={getActionColumnMenus(record)}
        />,
        
      ],
    },
  ]
  function getActionColumnMenus(record: API.AccountItem) {
    const commonMenus = [
      { key: 'HookUserAction', name: 'HookUserAction' },
      { key: 'CheckCookie', name: 'CheckCookie' },
      { key: 'OpenAccountHomePage', name: '打开账号主页' },
    ]
    const dyMenus = [
      { key: 'SmsSend', name: 'SmsSend' },
      { key: 'SmsValidate', name: 'SmsValidate' },
      { key: 'ShareCookie', name: 'ShareCookie' },
    ]
    if (record.type === 2) {
      return [...dyMenus, ...commonMenus]
    }
    return commonMenus
  }
  const [editItem, setEditItem] = useState<API.AccountItem | undefined>()
  const [validateSmsItem, setValidateSmsItem] = useState<API.AccountItem | undefined>()
  const [shareCookieItem, setShareCookieItem] = useState<API.AccountItem | undefined>()
  const [bindItem, setBindItem] = useState<API.AccountItem | undefined>()
  function smsSend(item: API.AccountItem) {
    IHttp.accountSmsSend(item.id).subscribe(
      console.log
    )
  }
  function updateHookUserAction(item: API.AccountItem) {
    IHttp.updateAccountHookUserAction(item.id).subscribe(
      res => {
        if (res.status) {
          ref.current?.reload()
        }
      }
    )
  }
  function checkAccountCookie(item: API.AccountItem) {
    IHttp.checkAccountCookie(item.id).subscribe(
      res => {
        if (res.status) {
          ref.current?.reload()
        }
      }
    )
  }

  function openAccountHomePage(item: API.AccountItem) {
    IHttp.openAccountHomePage(item.id).subscribe(
      res => {
        if (res.status) {
          Modal.warning({
            title: "提示",
            content: "账号首页已打开",
            closable: false,
            okText: "关闭首页",
            onOk(close) {
              IHttp.closeAccountHomePage(res.data).subscribe(
                () => close()
              )
            }
          })
        }
      }
    )
  }

  return (
    <>
      <PageContainer
        title={""}
        content={""}
      >
        <ProTable<API.AccountItem>
          // @ts-ignore
          actionRef={ref}
          columns={columns}
          request={(params, sorter, filter) => {
            // 表单搜索项会从 params 传入，传递给后端接口。
            console.log(params, sorter, filter);
            return firstValueFrom(
              IHttp.getAccountList().pipe(
                map(res => {
                  return {
                    data: res.data.list,
                    // success 请返回 true，
                    // 不然 table 会停止解析数据，即使有数据
                    success: true,
                    // 不传会使用 data 的长度，如果是分页一定要传
                    total: res.data.length,
                  }
                })
              )
            )
            // return Promise.resolve({
            //   data: tableListDataSource,
            //   success: true,
            // });
          }}
          toolbar={{
            search: {
              onSearch: (value: string) => {
                alert(value);
              },
            },
            actions: [
              <Button type="primary" onClick={() => {
                setEditItem({id: 0, name: "", type: 1, status: 0})
              }}>添加</Button>
            ],
          }}
          rowKey="id"
          search={false}
        />
      </PageContainer>
      <AccountCreateForm
        item={editItem}
        onCancel={() => setEditItem(undefined)}
        onRefreshTable={() => {
          setEditItem(undefined)
          ref.current?.reload()
        }}
      />
      <DrawerForm
        width={360}
        title="Sms validate"
        open={Boolean(validateSmsItem)}
        onFinish={async (values) => {
          console.log(values)
          const res = await firstValueFrom(IHttp.accountSmsValidate(validateSmsItem?.id as number, values.code))
          setValidateSmsItem(undefined)
          return true
        }}
        drawerProps={{
          onClose: () => setValidateSmsItem(undefined)
        }}
      >
        <ProFormText name="code" label="code" rules={[{required: true}]}/>
      </DrawerForm>
      <DrawerForm
        width={360}
        title="Share cookie"
        open={Boolean(shareCookieItem)}
        onFinish={async (values) => {
          console.log(values)
          const res = await firstValueFrom(IHttp.shareAccountCookie(values.id, shareCookieItem?.cookie as string, values.token))
          setShareCookieItem(undefined)
          return true
        }}
        drawerProps={{
          onClose: () => setShareCookieItem(undefined)
        }}
      >
        <ProFormText initialValue={2} name="id" label="Remote Account ID" rules={[{required: true}]}/>
        <ProFormText initialValue={"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzA5MTEyNjU1LCJleHAiOjE3MDk3MTc0NTV9.SdjscSqKfyB_m6OiW_3pIaL8MSzM-pJfGhq2Mvwb6bk"} name="token" label="Token" rules={[{required: true}]}/>
      </DrawerForm>
    </>

  );
};

export default AccountList;
